package com.qianfeng.xinyihezi.xinyihezi.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.qianfeng.xinyihezi.xinyihezi.R;
import com.qianfeng.xinyihezi.xinyihezi.adapter.GoodRecycleAdapter;
import com.qianfeng.xinyihezi.xinyihezi.config.NetConfig;
import com.qianfeng.xinyihezi.xinyihezi.config.RetrofitInterface;
import com.qianfeng.xinyihezi.xinyihezi.model.GoodgoodBean;
import com.qianfeng.xinyihezi.xinyihezi.view.CircleTransform;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by 张静远 on 2016/11/12.
 */

public class GoodFragment extends Fragment implements TabLayout.OnTabSelectedListener, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private ImageView mImageView, mImageGoTop;
    private TabLayout mTabLayout;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private Retrofit mRetrofit;
    private RetrofitInterface mRetrofitInterface;
    private List<GoodgoodBean> mData;
    private GoodRecycleAdapter mAdapter;
    private ProgressDialog mDialog;
    private String result = "推荐";
    private int page = 1;
    private String[] TitleArr = new String[]{"推荐", "零食", "美妆", "创意", "数码", "读书", "饰品", "健康", "运动", "母婴", "卡通"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_good, null);
        initView(view);
        initData();
        setData();
        setListener();
        return view;
    }

    private void setData() {
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setListener() {
        mImageView.setOnClickListener(this);
        mTabLayout.setOnTabSelectedListener(this);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mImageGoTop.setOnClickListener(this);
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 3 && mImageGoTop.getVisibility() == View.VISIBLE) {
                    mImageGoTop.setAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_bottom_out));
                    mImageGoTop.setVisibility(View.GONE);
                } else if (dy < -3) {
                    mImageGoTop.setAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_bottom_in));
                    mImageGoTop.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initData() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mData = new ArrayList<>();
        mAdapter = new GoodRecycleAdapter(getActivity(), mData);
        for (int i = 0; i < TitleArr.length; i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(TitleArr[i]));
        }
        mRetrofit = new Retrofit.Builder()
                .baseUrl(NetConfig.BASE_LEFTCLASSIFT)
                .build();
        mRetrofitInterface = mRetrofit.create(RetrofitInterface.class);
        mDialog.show();
        loadData(1, 291);
        mAdapter.setLoadCallback(new GoodRecycleAdapter.ILoadCallback() {
            @Override
            public void onLoad() {
                page += 1;
                if (page <= 10) {
                    if (result.equals("推荐")) {
                        loadData(page, 291);
                    }
                    if (result.equals("零食")) {
                        loadData(page, 292);
                    }
                    if (result.equals("美妆")) {
                        loadData(page, 293);
                    }
                    if (result.equals("创意")) {
                        loadData(page, 294);
                    }
                    if (result.equals("数码")) {
                        loadData(page, 295);
                    }
                    if (result.equals("读书")) {
                        loadData(page, 296);
                    }
                    if (result.equals("饰品")) {
                        loadData(page, 297);
                    }
                    if (result.equals("健康")) {
                        loadData(page, 298);
                    }
                    if (result.equals("运动")) {
                        loadData(page, 299);
                    }
                    if (result.equals("母婴")) {
                        loadData(page, 301);
                    }
                    if (result.equals("卡通")) {
                        loadData(page, 300);
                    }
                } else {
                    page = 1;
                    Toast.makeText(getActivity(), "没有更多了!!!!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void loadData(int page, int key) {
        mRetrofitInterface.getGoodData(page, key).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string().toString();
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray data = jsonObject.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            GoodgoodBean bean = new GoodgoodBean();
                            JSONObject jsonObject1 = data.getJSONObject(i);
                            bean.goods_id = jsonObject1.getString("goods_id");
                            bean.image_url = jsonObject1.getString("image_url");
                            bean.p_price = jsonObject1.getString("p_price");
                            bean.like_count = jsonObject1.getString("like_count");
                            bean.share_url = jsonObject1.getString("share_url");
                            bean.short_name = jsonObject1.getString("short_name");
                            mData.add(bean);
                        }
                        // 刷新数据源
                        mSwipeRefreshLayout.setRefreshing(false);
                        mAdapter.notifyDataSetChanged();
                        mDialog.dismiss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void initView(View view) {
        mImageGoTop = (ImageView) view.findViewById(R.id.iv_good_gotop);
        Picasso.with(getActivity()).load(R.mipmap.ic_arrow_up).transform(new CircleTransform()).into(mImageGoTop);
        mImageView = (ImageView) view.findViewById(R.id.iv_good_search);
        mTabLayout = (TabLayout) view.findViewById(R.id.tab_good_navigation);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl_good_refresh);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_good_recycler);
        mDialog = new ProgressDialog(getActivity());
        mDialog.setMessage("加载中...");
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        result = null;
        mData.clear();
        String text = tab.getText().toString();
        result = text;
        mDialog.show();
        if (text.equals("推荐")) {
            loadData(1, 291);
        }
        if (text.equals("零食")) {
            loadData(1, 292);
        }
        if (text.equals("美妆")) {
            loadData(1, 293);
        }
        if (text.equals("创意")) {
            loadData(1, 294);
        }
        if (text.equals("数码")) {
            loadData(1, 295);
        }
        if (text.equals("读书")) {
            loadData(1, 296);
        }
        if (text.equals("饰品")) {
            loadData(1, 297);
        }
        if (text.equals("健康")) {
            loadData(1, 298);
        }
        if (text.equals("运动")) {
            loadData(1, 299);
        }
        if (text.equals("母婴")) {
            loadData(1, 301);
        }
        if (text.equals("卡通")) {
            loadData(1, 300);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onRefresh() {
        mData.clear();
        mDialog.show();
        if (result.equals("推荐")) {
            loadData(1, 291);
        }
        if (result.equals("零食")) {
            loadData(1, 292);
        }
        if (result.equals("美妆")) {
            loadData(1, 293);
        }
        if (result.equals("创意")) {
            loadData(1, 294);
        }
        if (result.equals("数码")) {
            loadData(1, 295);
        }
        if (result.equals("读书")) {
            loadData(1, 296);
        }
        if (result.equals("饰品")) {
            loadData(1, 297);
        }
        if (result.equals("健康")) {
            loadData(1, 298);
        }
        if (result.equals("运动")) {
            loadData(1, 299);
        }
        if (result.equals("母婴")) {
            loadData(1, 301);
        }
        if (result.equals("卡通")) {
            loadData(1, 300);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_good_search:
                Toast.makeText(getActivity(), "这个是干什么的啊???", Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_good_gotop:
                mRecyclerView.smoothScrollToPosition(0);
                mImageGoTop.setAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_bottom_out));
                mImageGoTop.setVisibility(View.GONE);
                break;
        }
    }
}
